package log

import (
	"flag"
	"os"

	"github.com/sirupsen/logrus"
)

// Implement flag.Value interface
type logLevel string

func newLogLevel(val string) *logLevel {
	p := new(string)
	*p = val
	return (*logLevel)(p)
}

func (l *logLevel) Set(s string) error {
	*l = logLevel(s)
	return SetLogLevel(s)
}

func (l *logLevel) String() string { return string(*l) }

func init() {
	// 有默认值，但是不会调用
	flag.Var(newLogLevel("info"), "log.level", "valid levels: [trace, debug, info, warn, error, fatal, panic]")

	// TODO 定制化
	logrus.SetLevel(logrus.InfoLevel) // default
	// logrus.SetReportCaller(true)
	logrus.SetFormatter(&logrus.JSONFormatter{})
	logrus.SetOutput(os.Stdout)
}

func SetLogLevel(l string) error {
	level, err := logrus.ParseLevel(l)
	if err != nil {
		return err
	}
	logrus.SetLevel(level)
	return nil
}
